/*
  Example 21.2
  Reading and writing data to Microchip 24LC256 EEPROMS over I2C
  tronixstuff.com/tutorials > Chapter 21
  CC by-sa v3.0 
*/

#include <Wire.h>     // for I2C
#define chip1 0x50    // device address for left-hand chip on our breadboard
#define chip2 0x51    // and the right

// always have your values in variables
unsigned int pointer = 69; // we need this to be unsigned, as you may have an address > 32767
byte d=0; // example variable to handle data going in and out of EERPROMS

void setup()
{
  Serial.begin(9600); // for screen output
  Wire.begin();   // wake up, I2C!
}

void writeData(int device, unsigned int add, byte data) 
// writes a byte of data 'data' to the chip at I2C address 'device', in memory location 'add'
{
  Wire.beginTransmission(device);
  Wire.send((int)(add >> 8));   // left-part of pointer address
  Wire.send((int)(add & 0xFF)); // and the right
  Wire.send(data);
  Wire.endTransmission();
  delay(10);
}

byte readData(int device, unsigned int add) 
// reads a byte of data from memory location 'add' in chip at I2C address 'device' 
{
  byte result;  // returned value
  Wire.beginTransmission(device); //  these three lines set the pointer position in the EEPROM
  Wire.send((int)(add >> 8));   // left-part of pointer address
  Wire.send((int)(add & 0xFF)); // and the right
  Wire.endTransmission();
  Wire.requestFrom(device,1); // now get the byte of data...
  result = Wire.receive();
  return result; // and return it as a result of the function readData
}

void loop()
{
  Serial.println("Writing data...");
  for (int a=0; a<20; a++)
  {
    writeData(chip1,a,a);
    writeData(chip2,a,a); // looks like a tiny EEPROM RAID solution!
  }
  Serial.println("Reading data...");
  for (int a=0; a<20; a++)
  {
    Serial.print("chip1 pointer ");
    Serial.print(a);
    Serial.print(" holds ");
    d=readData(chip1,a);
    Serial.println(d, DEC);
  }
   for (int a=0; a<20; a++)
  {
    Serial.print("chip2 pointer ");
    Serial.print(a);
    Serial.print(" holds ");
    d=readData(chip2,a);
    Serial.println(d, DEC);
  } 
}
